package com.android.camera.one.v2.initialization;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import com.android.camera.debug.Log;

import android.os.ConditionVariable;

public class OneCameraCloserManager implements ICloserManager {
	private final Log.Tag TAG = new Log.Tag("CloserManager");
	private final AtomicBoolean mClosed;
	private final AtomicBoolean mClosedState;
    private final AtomicInteger mCounter;
    private final ConditionVariable mRequestWait;
    
    private static final int WAIT_TIME = 500;
    
    public OneCameraCloserManager() {
    	mClosed = new AtomicBoolean(false);
    	mClosedState = new AtomicBoolean(false);
		mCounter = new AtomicInteger(0);
    	mRequestWait = new ConditionVariable(true);
    }

	@Override
	public void increaseCloserCounter() {
		if (mClosed.get()) return;
		int count = mCounter.incrementAndGet();
		Log.d(TAG, "increaseCloserCounter "+count);
		if (count == 1) {
			mRequestWait.close();
		}
	}

	@Override
	public void discreaseCloserCounter() {
		if (mClosed.get()) return;
		int count = mCounter.decrementAndGet();
		Log.d(TAG, "discreaseCloserCounter "+count);
		if (count == 0) {
			mRequestWait.open();
		}
	}
	
	@Override
	public boolean isClosed() {
		return mClosedState.get();
	}
	
	@Override
	public void close() {
		mClosedState.set(true);
		Log.d(TAG, "close E "+WAIT_TIME);
		mRequestWait.block(WAIT_TIME);
		Log.d(TAG, "close X");
		mClosed.set(true);
	}
}
